<?php

/**
 * Class MarkupProcessor takes care on processing post contents into various
 * output formats like HTML.
 *
 */
require_once 'markup/markdown.php';

final class MarkupProcessor
{
    /**
     * Strings that used as delimiter between summary part and the rest of the text.
     */
    const SUMMARY_DELIMITER = '<!--more-->';
    
    protected static $base_url = '';
    
    /**
     * Initialize some parameters
     *
     * @param string $base_url URL that should prepend all generated URLs related 
     *      to the site (images, hyperlinks etc)
     *      
     */
    public static function setBaseUrl($base_url)
    {
        self::$base_url = $base_url;
    }
    
    public static function getPostTitleHtml(Post $post)
    {
        return $post->title;
    }
    
    public static function  getPostSummaryHtml(Post $post)
    {
        return self::getPostPartHtml($post, 'summary');
    }
    
    public static function getPostCompleteHtml(Post $post)
    {
        $summary = self::getPostSummaryHtml($post);
        $rest = self::getPostPartHtml($post, 'rest');
        return $summary . $rest;
    }
    
    private static function getPostPartHtml(Post $post, $part)
    {
        
        // get post date
        $datetime = new DateTime($post->mod_time);
        $utime = (int) $datetime->format('U');
        $part_contents = '';
        
        $post_body = $post->Body->body;
        list($summary, $rest_text) = self::splitPostBody($post_body);
        
        if ($part === 'summary') {
            return self::renderPostText($summary);
        } else {
            return self::renderPostText($rest_text);
        }
    }
    
    /**
     * Render text to xhtml code.
     *
     * @param string $text input string
     * @return string
     */
    /* // deprecated
    public static function renderToXhtml($text)
    {
        return self::renderMarkup($text);
    }
	*/
    
    /**
     * Render text of post (html allowed etc).
     *
     * @param string $text
     * @return string
     */
    public static function renderPostText($text) 
    {
        // some preliminary processing
        $text = preg_replace('/!!\[([^]]+)\]\(([a-zA-Z0-9_.-]{1,150})\)/', 
            '![\\1]('.self::$base_url.'image/\\2)', $text);
        
        $text = preg_replace('/!!\[([^]]+)\]\(([a-zA-Z0-9_.-]{1,150})\/s\)/', 
            '[![\\1]('.self::$base_url.'image/small-preview/\\2)]('.self::$base_url.'image/\\2)', $text);
        
        $text = preg_replace('/!!\[([^]]+)\]\(([a-zA-Z0-9_.-]{1,150})\/m\)/', 
            '[![\\1]('.self::$base_url.'image/medium-preview/\\2)]('.self::$base_url.'image/\\2)', $text);
        
        $text = preg_replace('/\*\[([^]]+)\]\(([a-z0-9-]+)\)/',
            '[\\1]('.self::$base_url.'p/\\2/)', $text);
        
        return Markdown($text);
    }
    
    /**
     * Render text of comment (strict markup: no html allowed etc).
     *
     * @param unknown_type $text
     * @return string
     */
    public static function renderCommentText($text)
    {
        return Markdown(htmlspecialchars($text), $text);
    }
    
    /**
     * Splits posts body text into summary and rest text parts.
     * 
     * @return array list($summary, $rest)
     */
    protected static function splitPostBody($text)
    {
        $delim_pos = strpos($text, self::SUMMARY_DELIMITER);
        if (FALSE == $delim_pos) {
            return array($text, '');
        }
        $summary = substr($text, 0, $delim_pos-1);
        $rest = substr($text, 
            $delim_pos+strlen(self::SUMMARY_DELIMITER)
            );
        return array($summary, $rest);
    }
    
    /*
    protected static function renderMarkup($text)
    {
        require_once 'markup/markdown.php';
        return Markdown(str_replace(array('&', '<'), array('&amp;', '&lt;'), $text));
        //return Markdown($text);
    }
    */
    
    /**
     * Find time of most fresh comment in the comments tree.
     *
     * @param array $comments
     * @param DateTime $last_time
     * @return DateTime
     */
    private static function findLatestComment($comments, $last_time)
    {
        foreach ($comments as $comment) {
            $comment_time = date_create($comment['time']);
            if ($comment_time > $last_time) {
                $last_time = $comment_time;
            }
            $new_time = self::findLatestComment($comment['subcomments'], $last_time);
            if ($new_time > $last_time) {
                $last_time = $new_time;
            }
        }
        return $last_time;
    }
    
}
?>
